package com.ruoyi.hyg.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.hyg.domain.FreeResource;
import com.ruoyi.hyg.service.IFreeResourceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 免费资料Controller
 *
 * @author ruoyi
 * @date 2025-08-13
 */
@RestController
@RequestMapping("/hyg/resource")
public class FreeResourceController extends BaseController
{
    @Autowired
    private IFreeResourceService freeResourceService;
    
    /**
     * 查询免费资料列表
     */
    @PreAuthorize("@ss.hasPermi('hyg:resource:list')")
    @GetMapping("/list")
    public TableDataInfo list(FreeResource freeResource)
    {
        startPage();
        List<FreeResource> list = freeResourceService.selectFreeResourceList(freeResource);
        return getDataTable(list);
    }
    
    /**
     * 导出免费资料列表
     */
    @PreAuthorize("@ss.hasPermi('hyg:resource:export')")
    @Log(title = "免费资料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FreeResource freeResource)
    {
        List<FreeResource> list = freeResourceService.selectFreeResourceList(freeResource);
        ExcelUtil<FreeResource> util = new ExcelUtil<FreeResource>(FreeResource.class);
        util.exportExcel(response, list, "免费资料数据");
    }
    
    /**
     * 获取免费资料详细信息
     */
    @PreAuthorize("@ss.hasPermi('hyg:resource:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(freeResourceService.selectFreeResourceById(id));
    }
    
    /**
     * 新增免费资料
     */
    @PreAuthorize("@ss.hasPermi('hyg:resource:add')")
    @Log(title = "免费资料", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FreeResource freeResource)
    {
        return toAjax(freeResourceService.insertFreeResource(freeResource));
    }
    
    /**
     * 修改免费资料
     */
    @PreAuthorize("@ss.hasPermi('hyg:resource:edit')")
    @Log(title = "免费资料", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FreeResource freeResource)
    {
        return toAjax(freeResourceService.updateFreeResource(freeResource));
    }
    
    /**
     * 删除免费资料
     */
    @PreAuthorize("@ss.hasPermi('hyg:resource:remove')")
    @Log(title = "免费资料", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(freeResourceService.deleteFreeResourceByIds(ids));
    }
    
    @GetMapping("/download/{id}")
    public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
        FreeResource resource = freeResourceService.selectFreeResourceById(id);
        if (resource == null || resource.getDel() == 1L) {
            response.sendError(HttpStatus.NOT_FOUND.value(), "资源不存在");
            return;
        }
        
        // 假设 fileUrl 是本地绝对路径（如 /data/uploads/file.pdf）
        Path filePath = Paths.get(resource.getFileUrl());
        if (!Files.exists(filePath)) {
            response.sendError(HttpStatus.NOT_FOUND.value(), "文件不存在");
            return;
        }
        
        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(resource.getTitle(), "UTF-8"));
        
        // 写入文件流
        Files.copy(filePath, response.getOutputStream());
    }
}
